﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Reflection;

namespace SimpleBoard.DependencyInjection
{
    public static class HostBuilderExtension
    {
        public static IHostBuilder UseAutoInjection(this IHostBuilder builder)
        {
            var ass = Assembly.GetCallingAssembly();

            var injectInfo = from type in ass.GetTypes()
                             let attr = type.GetCustomAttribute<InjectAsAttribute>()
                             where attr != null
                             select new { Type = type, InjectAs = attr.InjectionType };

            builder.ConfigureServices((context, services) =>
            {
                foreach (var injection in injectInfo)
                {
                    switch (injection.InjectAs)
                    {
                        case InjectionType.Transient:
                            services.AddTransient(injection.Type);
                            break;
                        case InjectionType.Singleton:
                            services.AddSingleton(injection.Type);
                            break;
                    }
                }
            });

            return builder;
        }
    }
}
